package com.lanju.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.lanju.entity.Appointment;



@Repository
public class AppointmentDao extends BaseDao<Appointment,String> {

    private static final Log log = LogFactory.getLog(AppointmentDao.class);
    @Autowired
	SessionFactory sessionFactory;
    
    @PersistenceContext(unitName = "financialmarketingUnit")
    private EntityManager entityManager;

    
    public void persist(Appointment transientInstance) {
        try {
            entityManager.persist(transientInstance);
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(Appointment persistentInstance) {
        try {
            entityManager.remove(persistentInstance);
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    
    public Appointment merge(Appointment detachedInstance) {
        try {
            Appointment result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public Appointment getById(String  id) {
        try {
            Appointment instance = entityManager.find(Appointment.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    /** 根据 参数获取,  */
    @SuppressWarnings("unchecked")
	public Appointment getByParam(Appointment appointment) {
        try {
        	StringBuffer sqld = new StringBuffer("select * from Appointment s where 1=1 ");
        /*    if(!StringUtils.isEmpty(appointment.getNickName())){
	             sqld.append(" and s.nickName like:1 ");
	          }
	        */
	         Query query = entityManager.createQuery(sqld.toString());
	/*        if(!StringUtils.isEmpty(appointment.getNickName())){
	              query.setParameter("1", "%"+appointment.getNickName()+"%");
	          }*/
         
            List<Appointment> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("findByParam fail",e);
            throw e;
        }
    }
        

    @SuppressWarnings("unchecked")
	public List<Map> getList(Map param, int pageSize, int offset) {
        StringBuffer sql = new StringBuffer(
        		 "select a.*, u.nickName 'creatorNickName'  ,u.nickName 'handlerNickName' ,u.phone 'handlerPhone' , h.`houseName` "
        		+ "from lj_appointment a "
        		+ "left join lj_user u on a.userId = u.userId "
        		+ "left join lj_house h on a.houseId = h.houseId where 1=1 ");
        if(!StringUtils.isEmpty(param.get("searchText"))){	//预约手机号
        	sql.append(" and a.phone like '%"+ param.get("searchText").toString() +"%' or a.nickName like '%"+param.get("searchText").toString() +"%' ");
        }
        sql.append(" order by a.createTime desc ");
    	SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
        return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).setFirstResult(offset).setMaxResults(pageSize).list();
    }
    
    public long getListCount(Map param) {
        try {
            StringBuffer sql = new StringBuffer(
           		 "select a.*, u.nickName 'creatorNickName'  ,h.nickName 'handlerNickName' ,h.phone 'handlerPhone'"
           		+ "from lj_appointment a "
           		+ "left join lj_user u on a.userId = u.userId "
           		+ "left join lj_user h on a.handlerId = h.userId where 1=1 ");
           if(param.get("phone")!=null){	//预约手机号
           	sql.append(" and a.phone like '%"+ param.get("phone").toString() +"%' ");
           }
           if(param.get("nickName")!=null){	//预约姓名
               sql.append(" and a.nickName like '%"+ param.get("nickName").toString() +"%' ");
           }
           if(param.get("creatorPhone")!=null){	//创建人手机号
           	sql.append(" and u.phone like '%"+ param.get("creatorPhone").toString() +"%' ");
           }
           if(param.get("handlerPhone")!=null){	//处理人手机号
           	sql.append(" and u.phone like '%"+ param.get("creatorPhone").toString() +"%' ");
           }
           if(param.get("handlerNickName")!=null){	//处理人姓名
           	sql.append(" and u.phone like '%"+ param.get("creatorPhone").toString() +"%' ");
           }
       
        	SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
        			
            return query.list().size();
            
        } catch (Exception e) {
            log.error("getList fail",e);
        }
        return 0;
    }

    public Map<String,Object> delAppointment(String id){
    	StringBuffer sql=new StringBuffer();
    	Map<String,Object> result=new HashMap<String, Object>();
    	try {
			sql.append("delete Appointment where appointmentId='"+id+"'");
			entityManager.createQuery(sql.toString()).executeUpdate();
			result.put("success",true);
		} catch (Exception e) {
			result.put("success",false);
			e.printStackTrace();
		}
		return result;
    }

}
